package com.rain.shoppingscienceproj.ui.activity.address;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import com.google.gson.Gson;
import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.Address;
import com.rain.shoppingscienceproj.module.JsonBean;
import com.rain.shoppingscienceproj.module.address.City;
import com.rain.shoppingscienceproj.module.address.County;
import com.rain.shoppingscienceproj.module.address.Province;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.login.LoginActivity;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.CustomTopBar;
import com.rain.shoppingscienceproj.utils.GetJsonDataUtil;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.OptionPicker;
import org.jaaksi.pickerview.util.Util;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;

public class AddressActivity extends BaseActivity implements OptionPicker.OnOptionSelectListener {

    @BindView(R.id.et_name)
    EditText mName;
    @BindView(R.id.et_phone)
    EditText mPhone;
    @BindView(R.id.et_address)
    EditText mAddress;
    @BindView(R.id.tv_area)
    TextView tv_area;
    @BindView(R.id.sw_check)
    Switch mCheck;
    private OptionPicker mPicker;
    private String provinceId, cityId, countyId, nickName = "", phone = "", detailedAddress = "", address = "";
    private int check = 0;//默认是2 不是0
    private boolean isFalg = false, isUp = false, isCheck = false;
    private Address addressData;

    @OnClick(R.id.ll_select_city)
    void address() {
        mPicker.setSelectedWithValues(provinceId, cityId, countyId);
        mPicker.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        loadingDialog = new LoadingDialog(this, "正在加载...");
        addressData = (Address) getIntent().getSerializableExtra("address");
        isCheck = getIntent().getBooleanExtra("isCheck", false);
        if (addressData == null) {
            isUp = false;
            TitleUtils.TitleRightText(this, "添加收货地址", "保存");
        } else {
            isUp = true;
            TitleUtils.TitleRightText(this, "修改收货地址", "保存");
            mName.setText(addressData.getAddressName());
            mPhone.setText(addressData.getAddressPhone());
            mAddress.setText(addressData.getAddressDetils());
            String[] strs = addressData.getAddress().split("-");
            provinceId = strs[0];
            cityId = strs[1];
            countyId = strs[2];
            address = provinceId + "-" + cityId + "-" + countyId;
            tv_area.setText(address);
            if (addressData.getStatus().equals("2")) {
                isFalg = true;
                mCheck.setChecked(true);
            } else {
                isFalg = false;
                mCheck.setChecked(false);
            }
        }
        if (isCheck) {
            isFalg = true;
            mCheck.setChecked(true);
            mCheck.setEnabled(false);
        } else {
            isFalg = false;
            mCheck.setChecked(false);
        }


        TitleUtils.mRightText.setTextColor(getResources().getColor(R.color.white));
        userInfo = GlobalData.getUserInfo();
        addressShow();
        initListener();

    }

    private void initListener() {
        mCheck.setOnCheckedChangeListener((buttonView, isChecked) -> isFalg = isChecked);

    }

    @OnClick(R.id.rl_right)
    void save() {
        Map<String, String> map = new HashMap<>();
        nickName = mName.getText().toString().trim();
        phone = mPhone.getText().toString().trim();
        detailedAddress = mAddress.getText().toString().trim();
        if (nickName.isEmpty()) {
            ToastUtils.showShortToast("请输入收货人姓名");
            return;
        }
        if (phone.isEmpty()) {
            ToastUtils.showShortToast("请输入联系方式");
            return;
        }
        if (tv_area.getText().toString().isEmpty()) {
            ToastUtils.showShortToast("请选择所在地区");
            return;
        }
        if (detailedAddress.isEmpty()) {
            ToastUtils.showShortToast("请输入详细地址");
            return;
        }
        if (isFalg)
            check = 2;
        else
            check = 0;
//        map.put("userId", userInfo.getUserId());
        map.put("token", userInfo.getToken());
        map.put("addressName", nickName);
        map.put("addressPhone", phone);
        map.put("address", address);
        map.put("addressDetils", detailedAddress);
        map.put("type", check + "");
        if (isUp) {
            map.put("addressId", addressData.getAddressId());
            upData(map);
        } else {
            addData(map);
        }
    }

    private void addData(Map<String, String> map) {
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .addAdress(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showLongToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int status = json.getInt("code");
                            if (status == 0) {
                                ToastUtils.showShortToast(json.getString("message"));
                                finish();
                            } else {
                                String jsonString = json.getString("message");
                                if (jsonString.contains("token")) {
                                    startActivitys(LoginActivity.class, 1);
                                    ToastUtils.showShortToast(jsonString);
                                } else {
                                    ToastUtils.showShortToast(jsonString);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void upData(Map<String, String> map) {
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .upaAdress(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showLongToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int status = json.getInt("code");
                            if (status == 0) {
                                ToastUtils.showShortToast(json.getString("message"));
                                finish();
                            } else {
                                String jsonString = json.getString("message");
                                if (jsonString.contains("token")) {
                                    startActivitys(LoginActivity.class, 1);
                                    ToastUtils.showShortToast(jsonString);
                                } else {
                                    ToastUtils.showShortToast(jsonString);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void addressShow() {
        mPicker = new OptionPicker.Builder(this, 3, this).create();
        final DefaultCenterDecoration decoration = new DefaultCenterDecoration(this);
        decoration.setLineColor(getResources().getColor(R.color.colorPrimary))
                .setLineWidth(1)
                .setMargin(Util.dip2px(this, 10), Util.dip2px(this, -3), Util.dip2px(this, 10),
                        Util.dip2px(this, -3));

        mPicker = new OptionPicker.Builder(this, 3, this).setInterceptor(new BasePicker.Interceptor() {
            @Override
            public void intercept(PickerView pickerView) {
                int level = (int) pickerView.getTag();
                pickerView.setVisibleItemCount(5);
                // setInterceptor 可以根据level区分设置pickerview属性
                pickerView.setCenterDecoration(decoration);
                pickerView.setColor(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.text_color));
                pickerView.setTextSize(15, 20);
            }
        }).create();
        int padding = Util.dip2px(this, 20);
        mPicker.setPadding(0, padding, 0, padding);
        Dialog dialog = mPicker.getPickerDialog();
        dialog.setCanceledOnTouchOutside(true);
        //dialog.getWindow().setGravity(Gravity.BOTTOM);

        // 自定义topbar
        CustomTopBar topBar = new CustomTopBar(mPicker.getRootLayout());
        topBar.getTitleView().setText("请选择城市");
        topBar.setDividerHeight(1).setDividerColor(Color.parseColor("#eeeeee"));
        mPicker.setTopBar(topBar);

        List<Province> data = createData();
        mPicker.setDataWithValues(data);
    }

    private List<Province> createData() {
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        List<Province> list = new ArrayList<>();
        for (int i = 0; i < jsonBean.size(); i++) {
            Province province = new Province();
            province.name = jsonBean.get(i).getName();
            province.citys = new ArrayList<>();
            for (int j = 0; j < jsonBean.get(i).getCityList().size(); j++) {
                City city = new City();
                city.name = jsonBean.get(i).getCityList().get(j).getName();
                city.counties = new ArrayList<>();
                for (int k = 0; k < jsonBean.get(i).getCityList().get(j).getArea().size(); k++) {
                    County county = new County();
                    county.name = jsonBean.get(i).getCityList().get(j).getArea().get(k);
                    city.counties.add(county);
                }
                province.citys.add(city);
            }
            list.add(province);
        }
        return list;
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }


    @Override
    public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {
        Province province = (Province) selectedOptions[0];
        City city = (City) selectedOptions[1];
        County county = (County) selectedOptions[2];
        provinceId = province.name;
        cityId = city.name;
        countyId = county.name;
        address = province.name + "-" + city.name + "-" + county.name;
        tv_area.setText(address);
    }
}
